package com.xxxx.seckill.controller;

import com.xxxx.seckill.pojo.SeckillMessage;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.rabbitmq.MQSender;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.service.ISeckillOrderService;
import com.xxxx.seckill.utils.JsonUtil;
import com.xxxx.seckill.vo.GoodsVo;
import com.xxxx.seckill.vo.RespBean;
import com.xxxx.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author lesile
 * @date 2022/4/21
 */
@RestController
@RequestMapping("/secKill")
public class SeckillController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    private RedisScript<Long> redisScript;
    private Map<Long, Boolean> EmptyStockMap = new HashMap<>();


    /**
     * @param usersId
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/doSeckill", method = RequestMethod.POST)
    public RespBean doSeckill(@RequestParam String usersId, @RequestParam Long goodsId) {
//        判断是否是重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + usersId + ":" + goodsId);
        if (seckillOrder != null) {
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记，减少Redis的访问
        if (EmptyStockMap.get(goodsId)) {
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //预减库存
        Long stock = (Long) redisTemplate.execute(redisScript, Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST);
        if (stock < 0) {
            EmptyStockMap.put(goodsId, true);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        SeckillMessage seckillMessage = new SeckillMessage(usersId, goodsId);
        mqSender.sendSeckillMessage(JsonUtil.object2JsonStr(seckillMessage));
        return RespBean.success(-1);
    }

    /**
     * 系统初始化,把商品库存数量加载到Redis
     */
    @RequestMapping(value = "/restartRedis", method = RequestMethod.GET)
    public RespBean restartRedis() {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if (CollectionUtils.isEmpty(list)) {
            return RespBean.error(RespBeanEnum.ACCESS_LIMIT_REACHED);
        }
        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().set("seckillGoods:" + goodsVo.getId(), goodsVo.getStockCount());
            EmptyStockMap.put(goodsVo.getId(), false);
            redisTemplate.delete("isStockEmpty:" + goodsVo.getId());
        });

        String ORDER = "order:" + "*";
        String PAY = "order:" + "*";

        Set<String> orderKeys = redisTemplate.keys(ORDER);
        Set<String> payKeys = redisTemplate.keys(PAY);
        redisTemplate.delete(orderKeys);
        redisTemplate.delete(payKeys);
        return RespBean.success();
    }

    /**
     * 获取秒杀结果
     *
     * @param tUser   用户信息
     * @param goodsId 商品主键
     * @return respBean
     */
    @GetMapping("getResult")
    @ResponseBody
    public RespBean getResult(User tUser, Long goodsId) {
        if (tUser == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        Long orderId = seckillOrderService.getResult(tUser, goodsId);
        return RespBean.success(orderId);
    }

}

